var openId = '';
var nickName = '';
var likeNums = 0;
var app = getApp();
Page({
  data: {
    currentTabIndex: 0,
    uploadInfo: [],
    studyCard: [],
    loveWall: [],
    lostThing: [],
    focusInput: false,
    height: '',
    isInput: false,
    inputValue: '',
    btnId: '',
    value: ''
  },
  onLoad() {
    this.getInfo();
    this.getOpenid();
    this.getUserInfo();
  },
  onTabsItemTap: function (event) {
    this.setData({
      currentTabIndex: event.currentTarget.dataset.index
    })
    this.getInfo()
  },
  btngetInfo() {
    var db = '';
    switch (this.data.currentTabIndex) {
      case 0:
        db = wx.cloud.database().collection('uploadInfo').orderBy('createTime', 'desc')
        break;
      case 1:
        db = wx.cloud.database().collection('studyCard').orderBy('createTime', 'desc')
        break;
      case 2:
        db = wx.cloud.database().collection('loveWall').orderBy('createTime', 'desc')
        break;
      case 3:
        db = wx.cloud.database().collection('lostThing').orderBy('createTime', 'desc')
        break;
    }
    db.get()
      .then(res => {
        switch (this.data.currentTabIndex) {
          case 0:
            this.setData({
              uploadInfo: res.data,
            })
            break;
          case 1:
            this.setData({
              studyCard: res.data,
            })
            break;
          case 2:
            this.setData({
              loveWall: res.data,
            })
            break;
          case 3:
            this.setData({
              lostThing: res.data,
            })
            break;
        }
      })
      .catch(res => {
        console.log('请求失败', res);
      })
  },
  getInfo() {

    wx.showToast({
      icon: 'loading',
      title: '加载中...',
    })
    var db = '';
    switch (this.data.currentTabIndex) {
      case 0:
        db = wx.cloud.database().collection('uploadInfo').orderBy('createTime', 'desc').skip(this.data.uploadInfo.length)
        break;
      case 1:
        db = wx.cloud.database().collection('studyCard').orderBy('createTime', 'desc').skip(this.data.studyCard.length)
        break;
      case 2:
        db = wx.cloud.database().collection('loveWall').orderBy('createTime', 'desc').skip(this.data.loveWall.length)
        break;
      case 3:
        db = wx.cloud.database().collection('lostThing').orderBy('createTime', 'desc').skip(this.data.lostThing.length)
        break;
    }
    db.get()
      .then(res => {
        console.log(res);
        if (res.data.length == 0) {
          wx.showToast({
            icon: 'none',
            title: '无更多数据',
            duration: 2000
          })
          wx.hideToast();
          return
        }
        switch (this.data.currentTabIndex) {
          case 0:
            this.setData({
              uploadInfo: this.data.uploadInfo.concat(res.data)
            })
            break;
          case 1:
            this.setData({
              studyCard: this.data.studyCard.concat(res.data)
            })
            break;
          case 2:
            this.setData({
              loveWall: this.data.loveWall.concat(res.data)
            })
            break;
          case 3:
            this.setData({
              lostThing: this.data.lostThing.concat(res.data)
            })
            break;
        }
      })
      .catch(res => {
        console.log('请求失败', res);
      })
    wx.hideToast()
  },
  previewImg: function (e) {
    let imgData = e.currentTarget.dataset.img;
    wx.previewImage({
      current: imgData[0],
      urls: imgData[1]
    })
  },
  //封装方法获取用户昵称
  getUserInfo() {
    wx.cloud.callFunction({
      name: 'getUserInfo',
      data: {
        openid: openId
      }
    }).then(res => {
      nickName = res.result.data[0].nickName
    }).catch(res => {
      console.log("云函数获取昵称失败", res);
    })

  },
  //封装方法（拿取用户openid）
  getOpenid() {
    wx.cloud.callFunction({
      name: 'getOpenid'
    }).then(res => {
      openId = res.result.openid;

    }).catch(res => {
      console.log("调用失败", res);
    })
  },
  async likeBtn(e) {
    var checkLogin = app.globalData.checkUserInfo
    var db = ''
    const _ = db.command
    var id = e.currentTarget.dataset.id
    var btnlikeIndex = e.currentTarget.dataset.index
    var likelist = [];
    var isHaveLove = false;
    if (checkLogin.nickName == undefined) {
      wx.showToast({
        icon: 'error',
        title: '请先登录',
      })
      return
    }
    wx.vibrateShort({
      type: 'heavy'
    });
    switch (this.data.currentTabIndex) {
      case 0:
        db = wx.cloud.database().collection('uploadInfo')
        break;
      case 1:
        db = wx.cloud.database().collection('studyCard')
        break;
      case 2:
        db = wx.cloud.database().collection('loveWall')
        break;
      case 3:
        db = wx.cloud.database().collection('lostThing')
        break;
    }

    let res = await db.doc(id).field({
      likeList: true
    }).get()
    // console.log("==1");
    likelist = res.data.likeList
    // console.log("==2");
    for (var i = 0; i <= likelist.length; i++) {
      if (likelist[i] == checkLogin.nickName) {
        // console.log("==3");
        wx.showToast({
          title: '取消成功',
          icon: 'none',
        })
        likelist.splice(i, 1);
        isHaveLove = true;
        break;
      }
    }
    if (!isHaveLove) {
      // console.log("===3");
      wx.showToast({
        title: '点赞成功',
        icon: 'none',
      })
      likelist.push(checkLogin.nickName)
    }

    switch (this.data.currentTabIndex) {
      case 0:
        await wx.cloud.callFunction({
          name: 'smallnoteLike',
          data: {
            id: id,
            likelist: likelist
          }
        })
          .then(res => {
            console.log("点赞成功", res);
          })
          .catch(res => {
            console.log("点赞失败", res);
          })
        // console.log("==4");
        break;
      case 1:
        await wx.cloud.callFunction({
          name: 'studyCardLike',
          data: {
            id: id,
            likelist: likelist
          }
        })
          .then(res => {
            console.log("点赞成功", res);
          })
          .catch(res => {
            console.log("点赞失败", res);
          })
        break;
      case 2:
        await wx.cloud.callFunction({
          name: 'loveWallLike',
          data: {
            id: id,
            likelist: likelist
          }
        })
          .then(res => {
            console.log("点赞成功", res);
          })
          .catch(res => {
            console.log("点赞失败", res);
          })
        break;
      case 3:
        await wx.cloud.callFunction({
          name: 'lostThingLike',
          data: {
            id: id,
            likelist: likelist
          }
        })
          .then(res => {
            console.log("点赞成功", res);
          })
          .catch(res => {
            console.log("点赞失败", res);
          })
        break;
    }
    // console.log("==5");
    this.btngetInfo();
    // console.log("==6");
    wx.hideToast()

  },
  inputFocus(e) {
    console.log('键盘弹起', e)
    this.setData({
      height: e.detail.height + 50,
      isInput: true
    })
  },
  inputBlur() {
    console.log('键盘收起')
    this.setData({
      isInput: false
    })
  },

  focusBtn: function (e) {
    var checkLogin = app.globalData.checkUserInfo
    if (checkLogin.nickName == undefined) {
      wx.showToast({
        icon: 'error',
        title: '请先登录',
      })
      return
    }
    // console.log(e);
    this.setData({
      btnId: e.currentTarget.dataset.btnid,
      focusInput: true,
      isInput: true
    })
  },

  inputValue(e) {
    // console.log(e);
    this.setData({
      inputValue: e.detail.value
    })
  },

  async btnSend() {
    if (this.data.inputValue == '') {
      wx.showToast({
        icon: 'error',
        title: '请输入评论内容',
        duration: 2000
      });
      return
    }else{
      wx.showToast({
        title: '评论成功',
      })
      wx.vibrateShort({
        type: 'heavy'
      });
    }
    var checkLogin = app.globalData.checkUserInfo;
    var commentList = [];
    var db = ''
    this.setData({
      value: ''
    })
    switch (this.data.currentTabIndex) {
      case 0:
        db = wx.cloud.database().collection('uploadInfo')
        break;
      case 1:
        db = wx.cloud.database().collection('studyCard')
        break;
      case 2:
        db = wx.cloud.database().collection('loveWall')
        break;
      case 3:
        db = wx.cloud.database().collection('lostThing')
        break;
    }
    let res = await db.doc(this.data.btnId).field({
      commentList: true
    }).get()

    commentList = res.data.commentList

    var comment = {
      nickName: checkLogin.nickName,
      value: this.data.inputValue
    }
    commentList.unshift(comment);
    console.log(commentList);

    switch (this.data.currentTabIndex) {
      case 0:
        await wx.cloud.callFunction({
          name: 'smallnoteComment',
          data: {
            id: this.data.btnId,
            commentList: commentList
          }
        })
          .then(res => {
            console.log("评论成功", res);
          })
          .catch(res => {
            console.log("评论失败", res);
          })
        break;
      case 1:
        await wx.cloud.callFunction({
          name: 'studyCardComment',
          data: {
            id: this.data.btnId,
            commentList: commentList
          }
        })
          .then(res => {
            console.log("评论成功", res);
          })
          .catch(res => {
            console.log("评论失败", res);
          })
        break;
      case 2:
        await wx.cloud.callFunction({
          name: 'loveWallComment',
          data: {
            id: this.data.btnId,
            commentList: commentList
          }
        })
          .then(res => {
            console.log("评论成功", res);
          })
          .catch(res => {
            console.log("评论失败", res);
          })
        break;
      case 3:
        await wx.cloud.callFunction({
          name: 'lostThingComment',
          data: {
            id: this.data.btnId,
            commentList: commentList
          }
        })
          .then(res => {
            console.log("评论成功", res);
          })
          .catch(res => {
            console.log("评论失败", res);
          })
        break;
    }

    this.btngetInfo();
    this.setData({
      inputValue: ''
    })
    wx.hideToast()
  },
  onPullDownRefresh() {
    wx.showNavigationBarLoading()
    setTimeout(() => {
      this.btngetInfo()
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }, 500);
  },
  onReachBottom() {
    wx.showToast({
      icon: 'loading',
      title: '加载中...',
      duration: 1500
    })
    this.getInfo()
  }
})